package com.zbkj.common.page;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName: PaginationUtil
 * @Description: TODO
 * @Author: XXXX
 * @Date: 2024/6/29 14:22
 * @Version: V1.0
 **/
public class PaginationUtil {

    /**
     * 将记录列表转换为指定类型的响应列表，并填充到CommonPage对象中。
     *
     * @param <T>         目标响应类型
     * @param records     记录列表
     * @param page        分页信息
     * @param targetClass 目标响应类型的Class对象
     * @return 包含转换后数据和分页信息的CommonPage对象
     */
    public static <T> CommonPage<T> convertAndFillPage(List<?> records, Page<?> page, Class<T> targetClass) {
        if (CollectionUtils.isEmpty(records)) {
            records = Lists.newArrayList();
        }
        List<T> responseList = records.stream()
                .map(record -> {
                    T response = newInstance(targetClass);
                    BeanUtils.copyProperties(record, response);
                    return response;
                })
                .collect(Collectors.toList());

        CommonPage<T> resultPage = new CommonPage<>();
        resultPage.setTotalPage(page.getPages());
        resultPage.setPage(page.getCurrent());
        resultPage.setLimit(page.getSize());
        resultPage.setTotal(page.getTotal());
        resultPage.setList(responseList);

        return resultPage;
    }

    // 辅助方法，用于实例化目标类型的对象
    private static <T> T newInstance(Class<T> clazz) {
        try {
            return clazz.getDeclaredConstructor().newInstance();
        } catch (InstantiationException | IllegalAccessException | NoSuchMethodException |
                 InvocationTargetException e) {
            throw new RuntimeException("Failed to instantiate object of class: " + clazz.getName(), e);
        }
    }

}
